package com.roy.netty.sworddemo.client;

import java.net.InetSocketAddress;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

public class SimpleNettyTCPClient extends AbstractTCPClient {

	public SimpleNettyTCPClient() {
		getBootstrap().handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				getChannelInitializer().initChannel(ch);
			}
		});
	}
	@Override
	public String doSend(InetSocketAddress address, String message,
			int waitMilliSeconds) throws Throwable {
		ChannelFuture channelFuture = getBootstrap().connect(address).sync();
		if (channelFuture.isSuccess()) {
			try {
				MessageSender sender = getMessageSender(
						channelFuture.channel());
				return sender.sendMessage(message, waitMilliSeconds);
			} finally {
				channelFuture.channel().close().sync();
			}
		} else {
			System.out.println("Connect server " + address + " error ");
			throw channelFuture.cause();
		}
	}

}
